# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: xguo

from coin.exchange.base.kr_rest.currency import NormCurrency, NativeCurrency
from coin.exchange.bitfinex_v2.kr_rest.constants import currency_list
from coin.exchange.bitfinex_v2.kr_rest.constants import quote_currency_list


def to_native_currency(currency_str: str):
  assert currency_str in currency_list, currency_str
  if currency_str in ("USDT", "EURT"):
    return currency_str[:-1]
  elif currency_str == 'QTUM':
    return 'QTM'
  elif currency_str == 'IOTA':
    return 'IOT'
  elif currency_str == 'BCHABC':
    return 'BAB'
  elif currency_str == 'BCHSV':
    return 'BSV'
  else:
    return currency_str


def from_native_currency(native_currency_str: str):
  if native_currency_str in ("USD", "EUR"):
    return native_currency_str + 'T'
  elif native_currency_str == 'QTM':
    return 'QTUM'
  elif native_currency_str == 'IOT':
    return 'IOTA'
  elif native_currency_str == 'BAB':
    return 'BCHABC'
  elif native_currency_str == 'BSV':
    return 'BCHSV'
  else:
    assert native_currency_str in currency_list, native_currency_str
    return native_currency_str


class BitfinexCurrency(NativeCurrency):
  _exchange = "Bitfinex"

  def __init__(self, currency, native_currency):
    assert currency in currency_list, currency
    assert currency.upper() == currency, currency
    assert to_native_currency(currency) == native_currency, (currency, native_currency)
    assert isinstance(native_currency, str), type(native_currency)
    super().__init__(currency, native_currency)

  @classmethod
  def FromStrCurrencyImpl(cls, currency, current_datetime):
    return BitfinexCurrency(from_native_currency(currency), to_native_currency(currency))

  @classmethod
  def FromStrNativeCurrencyImpl(cls, currency, current_datetime):
    if currency.startswith('f'):  # 'f' for funding currency
      currency = currency[1:]

    if currency in ("USD", "USDT"):
      return BitfinexCurrency("USDT", "USD")
    elif currency in ("EUR", "EURT"):
      return BitfinexCurrency("EURT", "EUR")
    elif currency in ("QTUM", "QTM"):
      return BitfinexCurrency("QTUM", "QTM")
    elif currency in quote_currency_list:
      return BitfinexCurrency(currency, currency)
    else:
      assert currency in currency_list, currency
      return BitfinexCurrency(from_native_currency(currency), currency)

  @classmethod
  def FromStrNativeCurrencyV1(cls, currency):
    currency = currency.upper()

    if currency in ("USD", "USDT"):
      return BitfinexCurrency("USDT", "USD")
    elif currency in ("EUR", "EURT"):
      return BitfinexCurrency("EURT", "EUR")
    elif currency in ("QTUM", "QTM"):
      return BitfinexCurrency("QTUM", "QTM")
    elif currency in quote_currency_list:
      return BitfinexCurrency(currency, currency)
    else:
      assert currency in currency_list, currency
      return BitfinexCurrency(from_native_currency(currency), currency)
